package com.xzy.springcloud.contoller;


import com.xzy.springcloud.pojo.CommonResult;
import com.xzy.springcloud.pojo.Payment;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;


@RestController
@Slf4j
public class OrderContoller {


    /*负载均衡在此类配置类中开启，
    *  此类作用是远程RPC调用*/
    @Autowired
    private RestTemplate template;

    //服务提供者地址
    public static final String PAYMENT_URL = "http://localhost:8001";
    
   // public static final String PAYMENT_URL = "http://CLOUD-GATEWAY";

    @PostMapping("/consumer/payment/create")



    public CommonResult<Payment> create( Payment payment){


        log.info(payment.getSerial());


        // 这里封装了一个payment对象 生产者在解析此次请求时需要加requestbody注解将这里的payment对象（url中用的是json传递这个对象）解析
        return template.postForObject(PAYMENT_URL+"/payment/create/",payment,CommonResult.class);
    }

    @GetMapping("/consumer/payment/get/{id}")
    public CommonResult<Payment> getPayment(@PathVariable("id") Long id){



        log.info(PAYMENT_URL+"/payment/get/"+id);

        //RestTemplate的两种使用（这里template.getForObject（）直接返回响应体中数据化成的对象，直接是CommonResult.class的实例化对象）

        return template.getForObject(PAYMENT_URL+"/payment/get/"+id,CommonResult.class);
    }


    @GetMapping("/consumer/payment/getForEntity/{id}")
    public CommonResult<Payment> getEntity(@PathVariable("id") Long id){

        //RestTemplate的两种使用（这里template.getForEntity()返回的是ResponseEntity对象，内部包含CommonResult.class实例化对象，同时包含了其他重要信息
        // 如：响应头，状态码，响应体等）
        ResponseEntity<CommonResult> entity = template.getForEntity(PAYMENT_URL+"/payment/create/",CommonResult.class);

        if (entity.getStatusCode().is2xxSuccessful()){//200成功
            return entity.getBody();   //返回请求体
        }else {
            return new CommonResult<>(444,"操作失败");
        }


    }


}
